<script lang="ts" setup>
import mcht from '@/api/mcht'
import { useHomeStore } from '@/store'

const { mchtNo, modifyEmployee, roleFlag } = storeToRefs(useHomeStore())
const ruleForm = ref()
const form = reactive({
  mchtNo: mchtNo.value,
  employeeName: '',
  employeeNo: '',
  phoneNumber: '',
  roleFlag: '',
  storeId: '',
  bindFlag: '0',
  qrCodeNo: '',
})

const rules = {
  employeeName: [
    { required: true, message: '请输入员工姓名' },
  ],
  phoneNumber: [
    { required: true, message: '请输入员工手机号' },
  ],
  roleFlag: [
    { required: true, message: '请选择员工角色' },
  ],
  storeId: [
    { required: true, message: '请选择员工归属' },
  ],
  qrCodeNo: [
    { required: true, message: '请选择码牌编号' },
  ],
}

const storeType = ref('')
const storeOptions = [
  { value: '03', text: '门店员工', type: 'S' },
  // { value: '02', text: '门店店长', type: 'S' },
]
const merchantOptions = [
  { value: '01', text:	'商户员工', type: 'M' },
  { value: '04', text: '商户业务主管', type: 'M' },
  // { value: '00', text: '商户管理员', type: 'M' },
]

// let storeOptions = []
// let merchantOptions = []
// if (mode.value === 'bind' || mode.value === 'unbind') {
//   storeOptions = [
//     { value: '03', text: '门店员工', type: 'S' },
//     { value: '02', text: '门店店长', type: 'S' },
//   ]
//   merchantOptions = [
//     { value: '01', text: '商户员工', type: 'M' },
//     { value: '04', text: '商户业务主管', type: 'M' },
//     { value: '00', text: '商户管理员', type: 'M' },
//   ]
// }else {
//   storeOptions = [
//     { value: '03', text: '门店员工', type: 'S' },
//   ]
//   merchantOptions = [
//     { value: '01', text: '商户员工', type: 'M' },
//     { value: '04', text: '商户业务主管', type: 'M' },
//   ]
// }

let originRoleOptions = storeOptions
if (roleFlag.value === '00' || roleFlag.value === '01' || roleFlag.value === '04') {
  originRoleOptions = originRoleOptions.concat(merchantOptions)
}

const roleOptions = ref<any[]>([])

watch(() => storeType.value, () => {
  // form.roleFlag = ''
  roleOptions.value = originRoleOptions.filter(option => option.type === storeType.value)
})

const mode = ref<string>('')
const SHGLYDisabled = ref<boolean>(false)
const MDDZDisabled = ref<boolean>(false)
const SHGLYDMDisabled = ref<boolean>(false)

onLoad((options: any) => {
  if (options.mode) {
    mode.value = options.mode
    if (mode.value === 'bind' || mode.value === 'unbind') {
        let storeOptions_add = 
          { value: '02', text: '门店店长', type: 'S' }
        
      let merchantOptions_add = 
          { value: '00', text: '商户管理员', type: 'M' }
        
      originRoleOptions.push(storeOptions_add)
      if (roleFlag.value === '00' || roleFlag.value === '01' || roleFlag.value === '04') {
        originRoleOptions.push(merchantOptions_add)
      }
    }

    if (options.mode === 'modify') {
      if (roleFlag.value === '00' && (modifyEmployee.value.roleFlag === '01' || modifyEmployee.value.roleFlag === '04')) {
        SHGLYDisabled.value = true
      }
      if (roleFlag.value === '00' && modifyEmployee.value.roleFlag === '03') {
        SHGLYDMDisabled.value = true
      }
      if (roleFlag.value === '02' && modifyEmployee.value.roleFlag === '03') {
        MDDZDisabled.value = true
      }
    }
  }
  else {
    mode.value = 'new'
    if (mode.value === 'new' && !form.storeId) {
      radioDisabled.value = true
    } else {
      radioDisabled.value = false
    }
  }
  if (options.employeeNo) {
    if (options.employeeNo === modifyEmployee.value.employeeNo) {
      form.employeeName = modifyEmployee.value.employeeName
      form.employeeNo = modifyEmployee.value.employeeNo
      form.phoneNumber = modifyEmployee.value.phoneNumber
      form.roleFlag = modifyEmployee.value.roleFlag
      form.storeId = modifyEmployee.value.storeId
      if (modifyEmployee.value.qrCodeNo) {
        form.bindFlag = '1'
        form.qrCodeNo = modifyEmployee.value.qrCodeNo
      }
    }
  }
})

const qrCodeOptions = ref([])
async function getQrcodeList(mchtNo: string) {
  const { data } = await mcht.getQrcodeList(mchtNo, form.employeeNo)
  if (data.status === 'success') {
    qrCodeOptions.value = data.data.qrCodeList.map((qrcode) => {
      return {
        text: qrcode,
        value: qrcode,
      }
    })
  }
}

async function submit() {
  ruleForm.value.validate().then(async ({ valid }: { valid: boolean }) => {
    if (valid) {
      if (mode.value === 'modify') {
        const { data } = await mcht.updateStaff(form)
        if (data.status === 'success') {
          // uni.showToast({
          //   icon: 'success',
          //   title: data.message,
          //   duration: 3000,
          // })

          uni.showModal({
            title: '提示',
            content: data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              }
            }
          });

        }
      }
      else if (mode.value === 'new') {
        const { data } = await mcht.addStaff(form)
        if (data.status === 'success') {
          // uni.showToast({
          //   icon: 'success',
          //   title: data.message,
          //   duration: 3000,
          // })
          uni.showModal({
            title: '提示',
            content: data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              }
            }
          });
        }
      }
      else if (mode.value === 'bind') {
        if (form.bindFlag === '0'){
          uni.showToast({
            title: '请选择绑定码牌',
            icon: 'none',
            duration: 2000
          });
          return
        }
        bind()
      }
      else if (mode.value === 'unbind') {
        if (form.bindFlag === '0') {
          uni.showToast({
            title: '请选择绑定码牌',
            icon: 'none',
            duration: 2000
          });
          return
        }
        unbind()
      }
    }
  })
}

async function unbind() {
  uni.showModal({
    title: '解绑确认',
    content: `您是否要解绑 ${form.employeeName} 的码牌？`,
    success: async (res) => {
      if (res.confirm) {
        const { data } = await mcht.unbindQrcode({
          mchtNo: mchtNo.value,
          employeeNo: form.employeeNo,
          roleFlag: form.roleFlag,
          qrCodeNo: form.qrCodeNo,
        })
        if (data.status === 'success') {
          // uni.showToast({
          //   icon: 'success',
          //   title: data.message,
          //   duration: 3000,
          // })
          uni.showModal({
            title: '提示',
            content: data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              }
            }
          });
        }
      }
      else if (res.cancel) {
        // console.log('用户点击取消')
      }
    },
  })
}

async function bind() {
  uni.showModal({
    title: '绑定确认',
    content: `您是否要为 ${form.employeeName} 绑定 ${form.qrCodeNo} 的码牌？`,
    success: async (res) => {
      if (res.confirm) {
        const { data } = await mcht.bindQrcode({
          mchtNo: mchtNo.value,
          employeeNo: form.employeeNo,
          storeId: form.storeId,
          roleFlag: form.roleFlag,
          qrCodeNo: form.qrCodeNo,
        })
        if (data.status === 'success') {
          // uni.showToast({
          //   icon: 'success',
          //   title: data.message,
          //   duration: 3000,
          // })
          uni.showModal({
            title: '提示',
            content: data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              }
            }
          });
        }
      }
      else if (res.cancel) {
        // console.log('用户点击取消')
      }
    },
  })
}

watch(() => form.storeId, () => {
  if (mode.value === 'new' && !form.storeId) {
    radioDisabled.value = true
  } else {
    radioDisabled.value = false
  }
  getQrcodeList(form.storeId)
})

onMounted(() => {
  getQrcodeList(mchtNo.value)
})

const radioDisabled = ref<boolean>(false)

</script>

<template>
  <div class="modify">
    <nut-form ref="ruleForm" :model-value="form" :rules="rules">
      <nut-form-item label="员工姓名" prop="employeeName" required custom-class="li-cell-box">
        <nut-input v-model="form.employeeName" class="nut-input-text" placeholder="请输入员工姓名" type="text"
          :disabled="mode === 'unbind' || mode === 'bind'" input-align="right" />
      </nut-form-item>
      <nut-form-item label="员工手机号" prop="phoneNumber" required custom-class="li-cell-box">
        <nut-input v-model="form.phoneNumber" class="nut-input-text" placeholder="请输入员工手机号" type="text"
          :disabled="mode === 'unbind' || mode === 'bind' || SHGLYDisabled || MDDZDisabled || SHGLYDMDisabled"
          input-align="right" max-length="11" />
      </nut-form-item>
      <nut-form-item label="归属" prop="storeId" required custom-class="li-cell-box">
        <store-casader v-model="form.storeId" v-model:type="storeType" hidden-self
          :disabled="mode === 'unbind' || mode === 'bind' || SHGLYDisabled || MDDZDisabled || SHGLYDMDisabled"
          inputAlign="right" :isScreening="mode === 'new'" />
      </nut-form-item>
      <nut-form-item label="员工角色" prop="roleFlag" required custom-class="li-cell-box">
        <option-select v-model="form.roleFlag" title="员工角色" :options="roleOptions"
          :disabled="mode === 'unbind' || mode === 'bind' || storeType === '' || MDDZDisabled || SHGLYDMDisabled"
          inputAlign="right" />
      </nut-form-item>
      <nut-form-item label="是否绑定码牌" prop="bindFlag" custom-class="li-cell-box">
        <nut-radio-group v-model="form.bindFlag" direction="horizontal" custom-class="li-cell-box-radio">
          <nut-radio label="0" :disabled="mode === 'modify' || mode === 'unbind' || radioDisabled">否</nut-radio>
          <nut-radio label="1" :disabled="mode === 'modify' || mode === 'unbind' || radioDisabled">是</nut-radio>
        </nut-radio-group>
      </nut-form-item>
      <nut-form-item v-if="form.bindFlag === '1'" label="码牌编号" prop="qrCodeNo" required custom-class="li-cell-box">

        <option-select v-if="mode === 'new' || mode === 'bind'" v-model="form.qrCodeNo" title="码牌编号"
          :options="qrCodeOptions" inputAlign="right" />
        <nut-input v-else v-model="form.qrCodeNo" class="nut-input-text" placeholder="请输入员工手机号" type="text" readonly
          disabled input-align="right" />
      </nut-form-item>
    </nut-form>
    <div class="actions">
      <div class="li-btn-tj shake_o"
        :class="{ 'li-btn-tj-not': ((mode === 'unbind' || mode === 'bind') && form.bindFlag === '0') }" @click="submit">
        {{ { new: '确定', unbind: '确定解绑', bind: '绑定', modify: '修改' }[mode] }}
      </div>
      <!-- <nut-button type="primary" block style="margin-bottom: 10px" @click="submit">
        {{ { new: '确定', unbind: '确定解绑', bind: '绑定', modify: '修改' }[mode] }}
      </nut-button> -->
    </div>
  </div>
</template>

<route lang="json">{
  "layout": "home",
  "style": {
    "navigationBarTitleText": "员工信息",
    "backgroundColorContent": "#f1f1f1"
  }
}</route>

<style lang="sass" scoped>
.modify
  .actions
    padding: 20px

:deep(.nut-radio)
  margin-bottom: 0!important
</style>
